import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LENOVO
 * Date: 2024-08-13
 * Time: 18:44
 */
class TreeNode{
    public int val;
    TreeNode left;
    TreeNode right;
}


public class Test {
    //二叉树的非递归后序遍历
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new LinkedList<>();
        if(root == null){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;

        while(!stack.isEmpty() || cur != null){
            while(cur !=  null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev){
                list.add(top.val);
                stack.pop();
                prev = top;
            }else{
                cur = top.right;
            }
        }
        return list;
    }
    public static void main(String[] args) {

    }
}
